package com.hyronjs.jiangbiao.antrus.spring.beans.factory.xml;

import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

public class BeansDtdResolver implements EntityResolver {
	private static final String DTD_EXTENSION = ".dtd";

	private static final String[] DTD_NAMES = {"spring-beans-2.0", "spring-beans"};



	public InputSource resolveEntity(String publicId, String systemId) throws IOException {
		if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
			int lastPathSeparator = systemId.lastIndexOf("/");
			for (int i = 0; i < DTD_NAMES.length; ++i) {
				int dtdNameStart = systemId.indexOf(DTD_NAMES[i]);
				if (dtdNameStart > lastPathSeparator) {
					String dtdFile = systemId.substring(dtdNameStart);
					try {
						Resource resource = new ClassPathResource(dtdFile, getClass());
						InputSource source = new InputSource(resource.getInputStream());
						source.setPublicId(publicId);
						source.setSystemId(systemId);
						return source;
					}
					catch (IOException ex) {
					}
				
				}
			}
		}

		// Use the default behavior -> download from website or wherever.
		return null;
	}
}
